package com.wlz.client;

import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import org.junit.Test;
import sun.rmi.runtime.Log;

import java.security.acl.Acl;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wlz
 * @date 2022-06-25  9:32 下午
 */
@Slf4j
public class AclOperationsClient extends StandaloneBase{

    private String zk_node = "/zk_node_1";

    /**
     *  用 world 模式创建节点
     * @throws Exception
     */
    @Test
    public void createWithAclTest() throws Exception{

        List<ACL> acls = new ArrayList<>();
        ACL acl = new ACL();
        Id id = new Id();
        id.setId("anyone");
        id.setScheme("world");

        int perms = ZooDefs.Perms.ADMIN | ZooDefs.Perms.READ;
        acl.setId(id);
        acl.setPerms(perms);
        acls.add(acl);

        String s = getZooKeeper().create(zk_node, "wlz".getBytes(), acls, CreateMode.PERSISTENT);
        log.info("create path: {}", s);
    }

    /**
     *  用授权模式创建节点
     *   如果未对连接添加 授权信息，节点创建失败
     *
     */
    @Test
    public void createWithAclTest2(){

        // 对连接信息 添加授权信息
        getZooKeeper().addAuthInfo("digest", "u400:p400".getBytes());

        List<ACL> acls = new ArrayList<>();
        ACL acl = new ACL();
        Id id = new Id();
        id.setId("u400:p400");
        id.setScheme("auth");

        int perms = ZooDefs.Perms.ADMIN | ZooDefs.Perms.READ | ZooDefs.Perms.WRITE;
        acl.setId(id);
        acl.setPerms(perms);
        acls.add(acl);

        String s = null;
        try {
            s = getZooKeeper().create("/zk_node_2", "wlz222".getBytes(), acls, CreateMode.PERSISTENT);
        } catch (KeeperException e) {
            log.error("error: {} ", e);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("create path: {}", s);
    }

    /**
     *  使用 授权方式 获取节点
     * @throws Exception
     */
    @Test
    public void createWithAclTest3() throws Exception{

        getZooKeeper().addAuthInfo("digest", "u400:p400".getBytes());

        byte[] data = getZooKeeper().getData("/zk_node_2", false, null);
        log.info(" get data: {}", new String(data));

    }

}

